package com.lq.ecoldchain.ui.mine.carInfo.carline.city

import android.app.Activity
import android.arch.lifecycle.MutableLiveData
import android.content.Intent
import com.lq.ecoldchain.base.viewmodel.BaseViewModel
import com.lq.ecoldchain.entity.City
import com.lq.ecoldchain.internet.BaseObserver

/*
*2019/1/3 0003  9:58
*function by lq
*/
class CityViewModel : BaseViewModel() {
    val list by lazy { ArrayList<City>() }
    val adapter by lazy { CityAllAdapter(list) }

    val isRefreshing by lazy { MutableLiveData<Boolean>() }

    init {
        obtainCityAll()
        adapter.setOnItemChildClickListener { _, view, position ->
            val activity = view.context as Activity
            //ARouter startActivity For Result
            //todo 添加关注线路
            addFollowCity(list[position].id)
            activity.finish()
        }
    }

   private fun addFollowCity(city:Int){
        BaseNetCore.ApiServiceImpl.addFollowCity(city).compose(RxTransformer.switchSchedulers()).subscribe(object:BaseObserver<String>(){
            override fun onSuccess(t: String?) {

            }

            override fun onFail(code: String) {

            }
        })
    }

    fun refreshData(){
        isRefreshing.value = true
        obtainCityAll()
    }


    private fun obtainCityAll() {
        BaseNetCore.ApiServiceImpl.obtainCityAll().compose(RxTransformer.switchSchedulers()).subscribe(object : BaseObserver<List<City>>() {
            override fun onSuccess(t: List<City>?) {
                isRefreshing.value = false
                if(!t.isNullOrEmpty()){
                    list.clear()
                    list.addAll(t)
                    adapter.notifyDataSetChanged()
                }
            }

            override fun onFail(code: String) {
                isRefreshing.value = false
            }
        })
    }

}